package com.lik888.controller;


import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.lik888.entity.User;
import com.lik888.entity.UserLogin;
import com.lik888.entity.po.R;
import com.lik888.service.IUserService;
import com.lik888.utils.JwtTool;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-10-24
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
   private IUserService userService;


    @Autowired
    private JwtTool jwtTool;
    @Qualifier("redisTemplate")
    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("/getUser")
    @PreAuthorize("hasAuthority('SELECT1')")
    public R<User> getUser() {
        User user = new User();
        user.setUsername("admin");
        user.setPassword("123456");
        return R.ok(user);
    }


    @PostMapping("/login")
    public R login(@RequestBody User user) {
        R login = userService.Login(user);
        return login;
    }

    /*退出登录*/
    @GetMapping("/loginOut")
    public R loginOut(HttpServletRequest req, HttpServletResponse res) {
        String token = req.getHeader("token");
        if (ObjectUtils.isEmpty(token)){
            token = req.getParameter("token");
        }
        /*获取security上下文中的用户信息；或者说获取当前线程的登录的用户信息，返回的对象是Authentication*/
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        /*这里*/
        if (authentication != null) {
            /*清除上下文*/
            new SecurityContextLogoutHandler().logout(req, res, authentication);
            /*清除redis*/
            String userId = authentication.getPrincipal().toString();
            Long userid = jwtTool.parseToken(userId);
            /*清除redis中的token*/
            String key = "securitydemo:user:"+userid;
            redisTemplate.delete(key);

        }
        return R.ok( "退出成功");
    }


}
